from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import  APIException,status,_
from datetime import datetime
# 存放token的表
from api.models import AccessToken

#重写AuthenticationFailed类，自定义响应状态码（认证报错类的状态码就可以随便定义了）
class AuthenticationFailed(APIException):
    status_code = status.HTTP_200_OK
    default_detail = _('Incorrect authentication credentials.')
    default_code = 'authentication_failed'

#web端的token认证
class JWTAuthentication(BaseAuthentication):
    def authenticate(self, request):
        '''
        所有token错误的状态码都是410，前端拿到状态码是410时要跳转到登录界面
        :param request:
        :return:
        '''
        # 获取token
        token = request.META.get("HTTP_TOKEN")  # 从请求头中获取
        if not token:
            raise AuthenticationFailed({'code':410,'error':'没有携带token'})
        code=410
        try:
            obj = AccessToken.objects.filter(token=token).first()
            if obj:
                now_time = datetime.now()
                exp_time = obj.exp_time
                if exp_time:
                    if now_time > exp_time:
                        raise AuthenticationFailed({'code': code, 'error': 'token过期了'})
                return ('admin',token)
            else:
                raise AuthenticationFailed({'code':code,'error':'token非法'})
        except Exception as e:
            raise AuthenticationFailed({'code':code,'error':'token有问题，请重新登录2'})